
var app = getApp();
Page({
  data: {
    fromMoments: false,  // 是否来自朋友圈
    loading: false       // 加载状态
  },

  onLoad(options) {
    console.log('朋友圈222')
  },

  // 处理用户授权
  async handleGetUserInfo(e) {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    try {
      // 1. 获取用户信息
      const userInfo = e.detail.userInfo;
      if (!userInfo) {
        throw new Error('用户拒绝了授权');
      }
      
      // 2. 获取登录code
      const { code } = await this.getLoginCode();
	  console.log(code)
      
      // 3. 发送到后端处理
      const { token, userData } = await this.sendToBackend(code, userInfo);
      console.log(token)
      // 4. 存储登录状态
      wx.setStorageSync('token', token);
      wx.setStorageSync('userInfo', userData);
      
      // 5. 跳转处理
      this.redirectAfterLogin();
      
    } catch (error) {
      console.error('登录失败:', error);
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 获取登录code
  getLoginCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            resolve({ code: res.code });
          } else {
            reject(new Error('获取code失败'));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 发送到后端
  sendToBackend(code, userInfo) {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'User/gowxLogin',
        method: 'POST',
        data: { code, userInfo },
        success: (res) => {
			console.log('asdfasdf',res)
          if (res.data.code == 1) {
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '登录失败'));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 登录后跳转
  redirectAfterLogin() {
    wx.reLaunch({
		url: '/vp_pz/pages/index/index'
	  });
  },

});